import base64
from datetime import datetime
import json
import argparse


def smoke_sj():
    try:
        parser = argparse.ArgumentParser()
        parser.add_argument('--data', type=str, default = None)
        args = parser.parse_args()
        json_data = json.loads(args.data)
        # json_data = json.loads('{"upPacketSN":-1,"deviceType":"","productId":"16699163","IMEI":"865714067190967","deviceId":"c84816dbaa9f48caab19cbe9a1b53e4e","protocol":"lwm2m","messageType":"dataReport","payload":{"APPdata":"NUEwMjEwQjAxMDg4LDIwMjMwODE2MDg0MTM4LDEwMCwtODYwLDcwLDAsMDk0NUZDNTIsMTcsMjUwOCwyMjQ="},"assocAssetId":"","tenantId":"2000000077","IMSI":"undefined","topic":"v1/up/ad","upDataSN":-1,"serviceId":"","timestamp":1692175318445}')
        if json_data.__contains__('payload'):
            APPdata = json_data.get('payload').get('APPdata')
            data = base64.b64decode(APPdata).decode(encoding ='utf-8',errors = 'strict')
            # 设备号
            number = json_data.get('IMEI')
            # 时间
            date = datetime.fromtimestamp(json_data.get('timestamp') / 1000.0)
            time = date.strftime('%Y-%m-%d %H:%M:%S')
            if '5A' not in data:
                return '格式不对'
            # 序号
            serialNumber = hex16To10int(data[4:6])
            # 命令
            cmd = yiHuo(data[6:8],serialNumber)
            # 数据
            code = data.split(",")
            # 解析数据
            parsingData = code[0]
            # 报警类型
            alarmTypeName = ""
            alarmType = ""
            # 报警内容
            content = ""
            # 烟雾浓度
            smokeConcentration = 0
            # 温度
            temperature = 0
            # 电池电量
            battery = code[2]
            # CSQ信号强度
            csq = code[7]
            # 报警表示
            alarmFlag = False
            # 报警数据
            json_alarm_data = {}
            # 正常数据
            json_normal_data = {}
            json_normal_data_arr = []
            # 返回数据
            data_json = {}

            if cmd == "0D":
                alarmTypeName = "自检报警"
                content = "自检报警"
                alarmFlag = True
            elif cmd == "01":
                alarmTypeName = "烟感火警"
                smokeConcentration = hex16To10int(yiHuo(parsingData[10:12],serialNumber))
                temperature = hex16To10int(yiHuo(parsingData[12:14],serialNumber));
                content = "烟感火警 信号强度:"+csq+" 电池余量:"+battery+" 温度:"+str(temperature)+" 烟雾浓度:"+str(smokeConcentration)
                alarmFlag = True
            elif cmd == "02":
                alarmTypeName = "烟感故障";
                smokeConcentration = hex16To10int(yiHuo(parsingData[10:12],serialNumber));
                content = "传感器故障 信号强度:"+csq+" 电池余量:"+battery+" 烟雾浓度:"+str(smokeConcentration);
                alarmFlag = True
            elif cmd == "03":
                alarmTypeName = "低电量报警"
                content = "低压故障"+" 电池余量:"+battery
                alarmFlag = True
            elif cmd == "0a":
                alarmTypeName = "拆除报警"
                content = "烟感拆除"
                alarmFlag = True
            elif cmd == "10":
                alarmTypeName = "烟感温度报警"
                content = "温感火警 信号强度:"+csq+" 电池余量:"+battery+" 温度:"+str(temperature)+" 烟雾浓度:"+str(smokeConcentration)
                alarmFlag = True
            elif cmd == "12":
                alarmTypeName = "烟感故障"
                content = "温度传感器故障"+" 温度:"+str(temperature)
                alarmFlag = True
            elif cmd == "00":
                temperature = hex16To10int(yiHuo(parsingData[18:20],serialNumber))

            if alarmFlag:
                json_alarm_data['alarmType'] = alarmType
                json_alarm_data['alarmTypeName'] = alarmTypeName
                json_alarm_data['content'] = content
                json_alarm_data['dataType'] = 'alarm'
                data_json["alarm"] = json_alarm_data
            normal_data = {}
            normal_data['name'] = '烟雾浓度变化'
            normal_data['value'] = smokeConcentration
            json_normal_data_arr.append(normal_data)
            normal_data = {}
            normal_data['name'] = '温度'
            normal_data['value'] = temperature
            json_normal_data_arr.append(normal_data)
            normal_data = {}
            normal_data['name'] = '电量'
            normal_data['value'] = battery
            json_normal_data_arr.append(normal_data)
            normal_data = {}
            normal_data['name'] = '信号'
            normal_data['value'] = csq
            json_normal_data_arr.append(normal_data)
            json_normal_data['paramInfo'] = json_normal_data_arr

            json_normal_data['dataType'] = 'normal'
            data_json['number'] = number
            data_json["normal"] = json_normal_data
            data_json['time'] = time
            return data_json
    except Exception as e:
        print(e)



# 十六进制转十进制返回int
def hex16To10int(code):
    To10code = int(code,16)
    return To10code



# 校验数字是技术还是偶数
def oddOrEven(a):
    if a % 2 !=0:
        return '奇数'
    else:
        return '偶数'


# 十六进制异或
def yiHuo(source,i):
    hexToInt = hex16To10int(source)


    hx = hex(hexToInt^i)[2:]

    odd = oddOrEven(i)
    if '偶数' == odd:
        hx = hx[1:2] + hx[0:1]
    if len(hx) == 1:
        hx = '0'+hx
    return hx

if __name__ == '__main__':
    print(smoke_sj())
